<?php

namespace App\Admin\Models;

use Illuminate\Database\Eloquent\SoftDeletes;

class ApiDocument extends Model
{
    use SoftDeletes;

    protected $guarded = []; 

    protected $casts = [
        'content' => \App\Admin\Casts\Json::class,
    ];

    public function changeKey(&$arr){
        $a = ['parent_id','order','created_at','updated_at','deleted_at','children'];
        foreach ($arr as $key => $value) {
            $arr[$key]['item'] = $value['children'];
            foreach(array_keys($value) as $value2){
                if (in_array($value2,$a)) {
                    unset($arr[$key][$value2]);
                }
            }
            if ($arr[$key]['item']) {
                $this->changeKey($arr[$key]['item']);
            }
        }
    }

    public function bindApiDocument(&$item, $showDocPages, $apiDocuments, $itemKey, $dirPathArr=[]){
        $contents = array_restruct($apiDocuments,'category_id');
        foreach ($item as $key => $value) {
            $id = $value['id'] ? $value['id'] : null;
            array_push($dirPathArr, $value['name']);
            if ($itemKey=='item') {
                unset($item[$key]['id']);
            }
            if (isset($contents[$id])) {
                if ($itemKey=='item') {
                    $contents[$id] = array_column($contents[$id], 'content');
                }
                foreach ($contents[$id] as $key2 => $value2) {
                    array_push($dirPathArr, $value2['name']);
                    $dirPath = implode('/', $dirPathArr);
                    $showdocUrl = $showDocPages[$dirPath] ? $showDocPages[$dirPath] : null;
                    $contents[$id][$key2]['showdoc_url'] = $showdocUrl;
                    $contents[$id][$key2]['request']['description'] = $showdocUrl;
                    array_pop($dirPathArr);
                }
                $item[$key][$itemKey] = $contents[$id]; 
                         
            } elseif (isset($item[$key][$itemKey]) && $item[$key][$itemKey]) {
                $this->bindApiDocument($item[$key][$itemKey], $showDocPages, $apiDocuments, $itemKey, $dirPathArr);
            }
            array_pop($dirPathArr);
        }
    }

    function matching($str){  
        $pattern = '/(\/\*\*).*?(\*\/)/is';
        preg_match_all($pattern, $str, $matches);
        $result = [];
        foreach ($matches[0] as $key => $value) {
            if (strstr($value, 'showdoc')) {
                array_push($result,$value);
            }
        }
        return array_filter($result);
    }

    public function updateApiDocument($showdoc){
        $apiDocumentCategory = app(ApiDocumentCategory::class);
        // 接收showdoc自动生成API文档的语法说明
        $showdoc = $this->matching($showdoc);
        $apiDocuments = [];
        foreach ($showdoc as $key => $value) {

            // 解析语法说明
            $data = trim(preg_replace('/\r?\n *\* */', ' ', $value));
            preg_match_all('/@([a-z|_]+)\s+(.*?)\s*(?=$|@[a-z|_]+\s)/s', $data, $matches);
            $info = array_combine($matches[1], $matches[2]);
            if (!$info) {
                continue;
            }

            // @catalog 生成文档要放到哪个目录。如果只是二级目录，则直接写目录名字。如果是三级目录，而需要写二级目录/三级目录，即用/隔开。如”一层/二层/三层”
            if (isset($info['catalog'])) {
                $catalog = trim(str_replace('*', '', $info['catalog'])).'/';
                $category_id = $apiDocumentCategory->createCategory($catalog);
            } else {
                $category_id = 0;
            }
            
            // @title   表示生成的文档标题
            if (isset($info['title'])) {
                $title = trim(str_replace('*', '', $info['title']));
            } else {
                $title = "";
            }

            // @description 是文档内容中对接口的描述信息
            if (isset($info['description'])) {
                $description = trim(str_replace('*', '', $info['description']));
            } else {
                $description = "";
            }

            // @method  接口请求方式。一般是get或者post
            if (isset($info['method'])) {
                $method = strtoupper(trim(str_replace('*', '', $info['method'])));
            } else {
                $method = "";
            }

            // @url 接口URL。不要在URL中使用&符号来传递参数。传递参数请写在参数表格中
            if (isset($info['url'])) {
                $url = config()->get('app.url').trim(str_replace('*', '', $info['url']));
            } else {
                $url = config()->get('app.url');
            }
            // 解析请求地址
            $infoUrl = parse_url($url);
            // protocol
            $protocol = $infoUrl['scheme'];
            // host
            $host = json_encode(explode('.', $infoUrl['host']), JSON_UNESCAPED_UNICODE);
            // port
            $port = isset($infoUrl['port']) ? $infoUrl['port'] : null;
            // path
            if (isset($infoUrl['path'])) {
                $infoUrl['path'] = trim(str_replace('*', '', $infoUrl['path']));
            } else {
                $infoUrl['path'] = "";
            }
            $path = json_encode(array_values(array_filter(explode('/', $infoUrl['path']))), JSON_UNESCAPED_UNICODE);

            // @header  可选。header说明。一行注释对应着表格的一行。用空格或者tab符号来隔开每一列信息。
            if (isset($info['header'])) {
                $header = trim(str_replace('*', '', $info['header']));
            } else {
                $header = "";
            }

            // @param   参数表格说明。一行注释对应着表格的一行。用空格或者tab符号来隔开每一列信息。
            $param = [];
            if (isset($info['param'])) {
                preg_match_all('/@(param+)\s+(.*?)\s*(?=$|@[a-z|_]+\s)/s', $data, $info['param']);
                foreach ($info['param'][2] as $key => $value) {
                    $values = array_filter(explode(' ', trim(str_replace('*', '', $value))));
                    if (isset($values[3])) {
                        $description = str_replace('<br/>', "\n", $values[3]);
                        array_push($param, [
                            'key'=>$values[0],
                            'value'=>"",
                            'disabled'=>[
                                'type'=>'boolean',
                                'default'=>false
                            ],
                            'description'=> $description,
                        ]);
                    }
                }
            }
            
            $param = json_encode($param, JSON_UNESCAPED_UNICODE);
            
            // @json_param  可选。当请求参数是json的时候，可增加此标签。请把json内容压缩在同一行内。
            if (isset($info['json_param'])) {
                $json_param = json_encode(trim(str_replace('*', '', $info['json_param'])), JSON_UNESCAPED_UNICODE);
            } else {
                $json_param = '[]';
            }
            
            // @return  返回内容。请把返回内容压缩在同一行内。如果是json，程序会自动进行格式化展示。 如果是非json内容，则原样展示。
            if (isset($info['return'])) {
                $return = trim(str_replace('*', '', $info['return']));
            } else {
                $return = "";
            }

            // @return_param    返回参数的表格说明。一行注释对应着表格的一行。用空格或者tab符号来隔开每一列信息。
            if (isset($info['return_param'])) {
                preg_match_all('/@(return_param+)\s+(.*?)\s*(?=$|@[a-z|_]+\s)/s', $data, $return_param);
            } else {
                $return_param = "";
            }

            // @remark  备注信息
            if (isset($info['remark'])) {
                $remark = trim(str_replace('*', '', $info['remark']));
            } else {
                $remark = "";
            }

            // @number  可选。文档的序号。
            if (isset($info['number'])) {
                $number = trim(str_replace('*', '', $info['number']));
            } else {
                $number = 0;
            }
            
            switch ($method) {
                case 'GET':
                    $content = '{
                        "name": "'.$title.'",
                        "request": {
                            "method": "'.$method.'",
                            "header": [],
                            "url": {
                                "raw": "'.$url.'",
                                "protocol": "'.$protocol.'",
                                "host": '.$host.',
                                "port": '.$port.',
                                "path": '.$path.',
                                "query": '.$param.'
                            }
                        },
                        "response": []
                    }';
                    break;
                   
                case 'POST':
                    $body = "[]";
                    if (json_decode($json_param, true)) {
                        $body = '{
                            "mode": "raw",
                            "raw": '.$json_param.',
                            "options": {
                                "raw": {
                                    "language": "json"
                                }
                            }
                        }';
                    } elseif (json_decode($param, true)) {
                        $body = '{
                            "mode": "formdata",
                            "formdata": '.$param.'
                        }';
                    }
                    $content = '{
                        "name": "'.$title.'",
                        "request": {
                            "method": "'.$method.'",
                            "header": [],
                            "body": '.$body.',
                            "url": {
                                "raw": "'.$url.'",
                                "protocol": "'.$protocol.'",
                                "host": '.$host.',
                                "port": '.$port.',
                                "path": '.$path.'
                            }
                        },
                        "response": []
                    }';
                    break;

                case 'PUT':
                    $body = "[]";
                    
                    if (json_decode($json_param, true)) {
                        $body = '{
                            "mode": "raw",
                            "raw": '.$json_param.',
                            "options": {
                                "raw": {
                                    "language": "json"
                                }
                            }
                        }';
                    } elseif (json_decode($param, true)) {
                        $body = '{
                            "mode": "formdata",
                            "formdata": '.$param.'
                        }';
                    }
                    $content = '{
                        "name": "'.$title.'",
                        "request": {
                            "method": "'.$method.'",
                            "header": [],
                            "body": '.$body.',
                            "url": {
                                "raw": "'.$url.'",
                                "protocol": "'.$protocol.'",
                                "host": '.$host.',
                                "port": '.$port.',
                                "path": '.$path.'
                            }
                        },
                        "response": []
                    }';
                    break;
                
                case 'DELETE':
                    $content = '{
                        "name": "'.$title.'",
                        "request": {
                            "method": "'.$method.'",
                            "header": [],
                            "url": {
                                "raw": "'.$url.'",
                                "host": '.$host.',
                                "port": '.$port.',
                                "path": '.$path.'
                            }
                        },
                        "response": []
                    }';
                    break;

                default:
                    $content = "";
                    break;
            }
            $apiDocumentData = [
                'name' => $title,
                'content' => $content,
                'url' => $url,
                'category_id' => $category_id
            ];
       
            $apiDocument = $this->where('name', $title)
                ->where('url', $url)
                ->first();
         
            if ($apiDocument) {
                $apiDocumentData['content'] = json_decode($content, true);
                $apiDocument->update($apiDocumentData);
            } else {
                $apiDocumentData['created_at'] = date('Y-m-d H:i:s');
                array_push($apiDocuments, $apiDocumentData);
            }
        }
        return $this->addAll($apiDocuments);
    }
}
